var Main = Class.create();
Main.prototype = {
	initialize: function() {
		this.components = [];
	},
	initializeComponents: function(element) {
		var children = (element || document.body).getElementsByTagName('*');
		for (var i = 0; i < children.length; i++) {
			try {
				var attr = children[i].getAttribute("yidong:component");
				if (attr) {
					this.components.push(children[i]);
					if (!main.scripts[attr]) {
						main.scripts[attr] = true;
					}
				}
			} catch (e) {}
		}

		this.loadComponents();
	},
	loadComponents: function() {
		for (var c in main.scripts) {
			if (main.scripts[c]) {
				var src = "/js/components/" + c + ".js";
				new Ajax.Request(src, {
					method: "get", 
					asynchronous: false, 
					onException: function(request, ex) {
						alert(ex);
					}
				});
				main.scripts[c] = false;
			}
		}
		window.setTimeout(this.renderComponents.bind(this), 5);
	},
	renderComponents: function() {
		for (var i = 0; i < this.components.length; i++) {
			var c = this.components[i];
			var type = c.getAttribute("yidong:component");
			c._component = eval("new " + type + "(c)");
			c._component.show();
		}
	}
};

var main = new Main();
main.scripts = {};
Event.observe(window, 'load', function() {main.initializeComponents();}, false);
